package com.woniu.service;

import com.woniu.been.entity.Courses;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

public interface CourseRepository extends JpaRepository<Courses, Long> {
    // 增加课程观看次数
    @Modifying
    @Transactional
    @Query("UPDATE Courses c SET c.viewCount = c.viewCount + 1 WHERE c.courseId = :courseId")
    int incrementViewCount(@Param("courseId") Long courseId);

    // 根据ID查询课程（同时获取最新的观看次数）
    Courses findByCourseId(Long courseId);

    /**
     * 将redis中的数据更新到数据库
     */
    @Modifying
    @Transactional
    @Query(value = "UPDATE courses SET view_count = :viewCount WHERE course_id = :courseId", nativeQuery = true)
    int updateViewCount(@Param("viewCount") Integer viewCount,@Param("courseId") Long courseId);

    // 按观看次数排序获取热门课程
    // 或直接指定数量
    @Query("SELECT c FROM Courses c ORDER BY c.viewCount DESC LIMIT 3")
    List<Courses> findTopByOrderByViewCountDesc (int limit);
    @Query("SELECT c.price FROM Courses c where c.courseId = :courseId")
    Double findPriceById(Long courseId);
}